package com.example.rbq.client

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.lib_core.task.SingleTask
import com.example.lib_core.task.Task
import com.example.lib_core.util.BufferConverter
import com.example.lib_core.util.JsonUtils
import com.example.lib_core.util.KitUtil
import com.example.lib_core.util.StringUtil
import com.example.rbq.R
import kotlinx.android.synthetic.main.activity_client.*
import java.io.IOException
import java.lang.NullPointerException
import java.net.DatagramPacket
import java.net.InetAddress

class ClientActivity : AppCompatActivity() {

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_client)

        btn_setting.setOnClickListener {
            val name = et_name.text.toString().trim()
            if (name.isNotEmpty()){
                val rpc = DebugRPC()
                rpc.method = "set_device_name"
                rpc.target = "9527"
                rpc.params["name"] = name
                EmulatorManage.callRPC(JsonUtils.gson.toJson(rpc))
            }
        }
        btn_get.setOnClickListener {
            Task.singleTask {
                val rpc = DebugRPC()
                rpc.method = "get_device_name"
                rpc.target = "9527"
                EmulatorManage.callRPC(JsonUtils.gson.toJson(rpc))
            }.success {
                Log.d("ClientActivity", "获取名字")
            }.error {
                Log.e("ClientActivity","获取名字失败"+it.message )
                it.printStackTrace()
            }.start()

        }
        btn_broadcast.setOnClickListener {
            //发送广播来获取端口号
            Task.singleTask {
                val rpc = DebugRPC()
                rpc.method = "get_ip"
                val buffer = JsonUtils.gson.toJson(rpc).toByteArray()
                EmulatorManage.client.sendBroadcast(buffer)
            }.success {
                tv_response.text = "发送广播成功,等待响应"
            }.error {
                it.printStackTrace()
                Log.e("xiao","${it.message}")
            }.start()
        }
        EmulatorManage.setOnResponseAction {rpc ->
            when(rpc.method){
                "get_device_name" -> {
                    tv_name.text = "设备名字:${rpc.params["name"]}"
                }
                "get_ip" -> {
                    val ip = rpc.params["ip"]
                    tv_response.text = "收到来自【$ip】的响应"
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        EmulatorManage.connectSever()
    }

    override fun onPause() {
        super.onPause()
        EmulatorManage.disconnectSever()
    }
}